#!/bin/bash
#
# dnsbl-milter  This shell script takes care of starting and stopping the
#		gkmilter
#
# Author:       George Koufoudakis <gkoufoud@yahoo.gr>
# $Id$
#
# description: gkmilter - Sendmail advance milter
# processname: gkmilter
# pidfile: /var/run/gkmilter/gkmilter.pid

# Source function library.
. /lib/lsb/init-functions

PROG="gkmtfirewall"
INSTPATH="/usr/sbin"
PID_FILE="/var/run/gkmtfirewall.pid"

CMD="$INSTPATH/$PROG"

RETVAL=0

if [[ ! -x "$INSTPATH/$PROG" ]]; then
	exit 0
fi

# set the stack size a bit lower
ulimit -s 1024

# set the number of open files higher
ulimit -n 64000

start() {
    #Check if already running
    if [ -e $PID_FILE ]; then
	echo "$PROG is already running. Abording";
	return 1;
    else
	echo -n "Starting $PROG"
	$CMD
	COUNTER=0
	while [ ! -e $PID_FILE -a $COUNTER -lt 10 ]; do
	    echo -n ".";
	    sleep 1;
	    let COUNTER=COUNTER+1
	done
	if [ -e $PID_FILE ]; then
	    echo " OK";
	    return 0;
	else
	    echo " Failed to start";
	    return 2;
	fi
    fi
}

stop() {
    if [ -e $PID_FILE ]; then
	echo -n "Stopping $PROG";
	kill -HUP `cat $PID_FILE`;
	COUNTER=0
	while [ -e $PID_FILE -a $COUNTER -lt 10 ]; do
	    echo -n "."
	    sleep 1;
	    let COUNTER=COUNTER+1
	done
	if [ -e $PID_FILE ]; then
	    echo " Failed to stop";
	    return 3;
	else
	    echo " OK";
	    return 0;
	fi
    else
	echo "$PROG is not running.";
	return 4;
    fi
}

status() {
    pid1=`ps aux | grep $INSTPATH/$PROG | grep -v grep | head -1 | awk '{print $2}'`

    if [ -e $PID_FILE ]; then
	pid2=`cat $PID_FILE`
    fi

    if [ -z "$pid1" ]; then
	if [ -z "$pid2" ]; then
	    echo "$PROG is not running";
	    return 0;
	else
	    echo "$PROG is not running but pidfile exists (unclean shutdown)";
	    echo "Try to delete pidfile (rm $PID_FILE)"
	    return 1;
	fi
	return 0;
    else
	if [ -z "$pid2" ]; then
	    echo "$PROG is running but there is no pidfile";
	    echo "Try to restart $PROG (/etc/init.d/$PROG restart)";
	    return 2
	fi
	if [ $pid1 -ne $pid2 ]; then
	    echo "$PROG is running but there is an error in pidfile";
	    echo "Try to restart $PROG (/etc/init.d/$PROG restart)";
	    return 3;
	else
	    echo "$PROG is running (pid=$pid1)";
	    return 0;
	fi	
    fi
    
}

case "$1" in
  start)
	start
        ;;
  stop)
	stop
        ;;
  status)
	status
	;;
  restart)
	stop
	start
	RETVAL=$?
	;;
  *)
        echo $"Usage: $0 {start|stop|restart|status}"
        exit 1
esac

exit $RETVAL

